import { Layout } from "@/components/layout/layout";
import ProfileLayout from "@/components/layout/profileLayout";
import { showToast } from "@/components/toast";
import withAuth, { getServerSideProps } from "@/hoc/withAuth";
import { useGlobalState, useHttp } from "@/hooks";
import { eventBus } from "@/utils/event";
import { Visibility, VisibilityOff } from "@mui/icons-material";
import { Image, Button, Checkbox, Input } from "@nextui-org/react";
import type { NextPage } from "next";
import Link from "next/link";
import { useEffect, useRef, useState } from "react";

const ProfilePage: NextPage = () => {
  const userInfo = useGlobalState("user", "userInfo");
  const [name, setName] = useState(userInfo.name);

  useEffect(() => {
    setName(userInfo.name);
  }, [userInfo.name]);

  const [isChangePwd, setIsChangePwd] = useState(false);
  const fileRef = useRef<HTMLInputElement | null>();
  const [isVisibles, setIsVisibles] = useState({ one: false, two: false });
  const [passwords, setPasswords] = useState({ one: "", two: "" });
  const { isLoading, http } = useHttp();
  const updatePasswords = (val: { one?: string; two?: string }) => {
    setPasswords((old) => ({ ...old, ...val }));
  };

  const [avatarUrl, setAvatarUrl] = useState<
    string | undefined | ArrayBuffer
  >();
  useEffect(() => {
    userInfo.avatarData && setAvatarUrl(userInfo.avatarData);
  }, [userInfo.avatarData]);

  const updateIsVisibles = (val: { one?: boolean; two?: boolean }) => {
    setIsVisibles((old) => ({ ...old, ...val }));
  };

  const handleChooseFile = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    if (!/^image/.test(file.type)) {
      showToast("Please select an image file");
      return;
    }

    const reader = new FileReader();
    reader.onload = (e) => {
      const dataURL = e.target?.result;
      if (!dataURL) return;
      setAvatarUrl(dataURL);
    };
    reader.readAsDataURL(file);
  };

  Object.assign(console, { eventBus });

  const handleSave = async () => {
    const formData = new FormData();
    if (name === "") {
      showToast("Please enter name");
      return;
    }
    if (isChangePwd) {
      if (passwords.one !== passwords.two) {
        showToast("Password is not match");
        return;
      } else if (!passwords.one) {
        showToast("Please enter new password");
        return;
      }

      formData.append("password", passwords.one);
    }

    formData.append("name", name);

    // update user info`
    const file = fileRef.current?.files?.[0];
    if (file) {
      formData.append("avatar", file);
    }

    const res = await http.post("/api/user/profile", formData, {
      axiosOptions: {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      },
    });
    if (res?.success) {
      if (isChangePwd && formData.get("password")) {
        showToast({
          message: "Password has been changed, login again please",
          duration: 4000,
        });
        eventBus.emit("logout", true);
      } else {
        eventBus.emit("userinfo", true);
      }
    }
    // console.log("🚀 ~ handleSave ~ res:", res);
  };

  return (
    <ProfileLayout>
      <div className="profile-content flex flex-col flex-1">
        <div className="profile-bd flex-1">
          <div
            className="grid grid-cols-2 m-[50px]"
            style={{ lineHeight: "40px", rowGap: 100, columnGap: 50 }}
          >
            <div className="grid">
              <div className="flex">
                <div className="label w-24 flex-0">Email:</div>
                <div className="value flex-1">
                  <Input
                    fullWidth
                    isClearable={false}
                    variant="bordered"
                    radius="lg"
                    size="md"
                    type="text"
                    isRequired
                    disabled
                    value={userInfo.email}
                    classNames={{
                      base: "bg-[#f9f9f9]",
                    }}
                    onChange={(e) => e.target.value && setName(e.target.value)}
                    // contentLeft={<Mail fill="currentColor" />}
                  />
                </div>
              </div>
            </div>
            <div className="grid">
              <div className="flex">
                <div className="label w-24 flex-0">Name:</div>
                <div className="value flex-1">
                  <Input
                    fullWidth
                    color="default"
                    isClearable={true}
                    variant="bordered"
                    radius="lg"
                    size="md"
                    type="text"
                    isRequired
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                    // contentLeft={<Mail fill="currentColor" />}
                  />
                </div>
              </div>
            </div>
            <div className="grid col-span-2">
              <div className="flex">
                <div className="label w-24 flex-0">Avatar:</div>
                <div className="value flex-1 relative">
                  <input
                    type="file"
                    ref={(el) => (fileRef.current = el)}
                    style={{
                      position: "absolute",
                      zIndex: 100,
                      width: "100px",
                      height: "50px",
                      opacity: 0,
                    }}
                    onChange={handleChooseFile}
                  />
                  <Button color="primary" size="md">
                    Select
                  </Button>

                  {avatarUrl && (
                    <Image
                      className="mt-4"
                      isZoomed
                      width={80}
                      // @ts-ignore
                      src={avatarUrl}
                      alt="avatar"
                    />
                  )}
                </div>
              </div>
            </div>
            <div className="grid col-span-2">
              <div className="flex">
                <div className="check-wrap">
                  <span className="mr-4">Change password:</span>
                  <Checkbox
                    value="checkPwd"
                    size="md"
                    color="primary"
                    checked={isChangePwd}
                    onChange={(e) => setIsChangePwd(e.target.checked)}
                  />
                </div>

                <div
                  className="inputs flex-1 ml-4"
                  style={{ display: isChangePwd ? "block" : "none" }}
                >
                  <Input
                    fullWidth
                    color="default"
                    variant="bordered"
                    radius="lg"
                    type={isVisibles.one ? "text" : "password"}
                    isRequired
                    size="md"
                    label="New Password"
                    value={passwords.one}
                    onChange={(e) => updatePasswords({ one: e.target.value })}
                    endContent={
                      <button
                        className="focus:outline-none"
                        type="button"
                        onClick={() =>
                          updateIsVisibles({ one: !isVisibles.one })
                        }
                      >
                        {isVisibles.one ? (
                          <VisibilityOff className="text-md text-default-400" />
                        ) : (
                          <Visibility className="text-md text-default-400" />
                        )}
                      </button>
                    }
                  />

                  <Input
                    className="mt-4"
                    fullWidth
                    color="default"
                    variant="bordered"
                    radius="lg"
                    type={isVisibles.two ? "text" : "password"}
                    isRequired
                    size="md"
                    label="Repeated New Password"
                    value={passwords.two}
                    onChange={(e) => updatePasswords({ two: e.target.value })}
                    endContent={
                      <button
                        className="focus:outline-none"
                        type="button"
                        onClick={() =>
                          updateIsVisibles({ two: !isVisibles.two })
                        }
                      >
                        {isVisibles.two ? (
                          <VisibilityOff className="text-md text-default-400" />
                        ) : (
                          <Visibility className="text-md text-default-400" />
                        )}
                      </button>
                    }
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
        <div className="profile-ft text-right flex-0 m-6">
          <Button
            color="primary"
            isLoading={isLoading}
            size="md"
            onClick={handleSave}
          >
            Save
          </Button>
        </div>
      </div>
    </ProfileLayout>
  );
};

export default withAuth(ProfilePage);

export { getServerSideProps };
